package com.ly.blog_common.utils;

import com.ly.blog_common.excel.ExcelCore;
import com.ly.blog_common.excel.ExcelExportType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * excel表格导出
 *
 * @author ly
 * create at 2021/8/30 - 10:20
 **/
@Slf4j
public class ExcelUtils {


    /**
     *
     * @param title
     * @param className
     * @param list
     * @param excelExportType
     * @param response
     * @param request
     * @throws IOException
     */
    public static void excelExport(String title,
                                   Class className,
                                   List list,
                                   ExcelCore excelCore,
                                   ExcelExportType excelExportType,
                                   HttpServletResponse response,
                                   HttpServletRequest request) throws IOException {
        OutputStream out = response.getOutputStream();
        try {
            HSSFWorkbook hss = new HSSFWorkbook();
            hss = excelCore.exportExcel(title,className,list,excelExportType);
            String disposition = "attachment;filename=";
            if (request != null && request.getHeaders("USER-AGENT") != null
                    && StringUtils.contains(request.getHeader("USER-AGENT"), "Firefox")) {
                disposition += new String((title + ".xls").getBytes(), "ISO8859-1");
            } else {
                disposition += URLEncoder.encode(title + ".xls", "UTF-8");
            }

            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-disposition", disposition);
            hss.write(out);
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            out.close();
        }
    }


}
